/* MessageUtils.js
 *
 * Copyright 2006, Tim Dwelle.
 *
 * Licensed under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in
 * compliance with the License.  You may obtain a copy of
 * the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in
 * writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied.  See
 * the License for the specific language governing
 * permissions and limitations under the License.
 *
 */

$package("dowry.util");

/**
 * Helper class to get locale-specific string messages.
 * This implementation uses a simple map lookup... however,
 * it wraps the calls to the map such that if no matching
 * message is found, it returns the key itself.  As with the
 * other classes in the <code>dowry.util</code> pacakge, if
 * you would rather use a different mechanism for
 * internationalization, you can replace with an alterantive
 * implementation.
 *
 */
$class("MessageUtils").$as(
{
    _bundle : null,

    /**
     * Constructs a new MessageUtils instance with the
     * provided locale-specific bundle.
     *
     * @param  bundle  a resource bundle as a map of keys
     *                 to locale-specific string messages
     *
     */
    MessageUtils : function(bundle)
    {
        if (!bundle)
        {
            bundle = new Object();
        }
        this._bundle = bundle;
    },

    /**
     * Returns the message for the specified key... or
     * if no matching message is found, it returns the
     * key itself.
     *
     * <p>
     * This method optionally takes in arguments for the
     * message, and will be substituted into the string
     * using Java's basic MessageFormat pattern of
     * <code>{0}</code>, etc.  More complex formatting
     * instructions, however, are not currently supported.
     * </p>
     *
     * @param key   the key to the message in the bundle
     *
     * @param args  (optional) arguments used to construct
     *              the message
     *
     * @return      the localized string message
     *
     */
    getMessage : function(key, args)
    {
        var msg = null;

        if (key)
        {
            msg = this._bundle[key];

            if (msg && args)
            {
                for (var i=0; i < args.length; i++)
                {
                    msg = msg.replace("{"+(i)+"}", args[i]);
                }
            }

            if (!msg)
            {
                msg = key;
            }
        }

        return msg;
    }
});